import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.io as pio
from sklearn.preprocessing import StandardScaler
import optuna
import optuna.visualization as vis
from sklearn.model_selection import cross_val_score
from catboost import CatBoostRegressor
import warnings

warnings.filterwarnings('ignore')
# 显示中文及负号
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


# def data_scale(df):
#     # 创建标准化器
#     scaler = StandardScaler()
#     # 标准化数据
#     features_scaled = scaler.fit_transform(df)
#
#     return features_scaled


def objective(trial):
    # 设置超参数范围
    param = {
        'iterations': trial.suggest_int('iterations', 100, 1000),
        'learning_rate': trial.suggest_float('learning_rate', 0.01, 0.3),
        'depth': trial.suggest_int('depth', 4, 10),
        'l2_leaf_reg': trial.suggest_float('l2_leaf_reg', 1e-3, 10.0),
    }
    # 初始化CatBoost模型
    cat_model = CatBoostRegressor(**param, verbose=0, random_state=42, loss_function='RMSE')

    # 交叉验证得分
    score = cross_val_score(cat_model, X_train, y_train, cv=3, scoring='neg_mean_squared_error')

    # 返回平均误差
    return -score.mean()


# 读取训练数据
train_data = pd.read_excel('../data/Q4_train.xlsx')
data = train_data[(50000 <= train_data['频率，Hz']) & (train_data['频率，Hz'] <= 500000)]
X_train = data.iloc[:, :-1]
# X_train = data_scale(data.iloc[:, :-1])
y_train = data['磁芯损耗，w/m3'].values

# 超参数优化
study = optuna.create_study(direction='minimize')
# study = optuna.create_study(sampler=optuna.samplers.CmaEsSampler(), direction='minimize')
study.optimize(objective, n_trials=500)

plt.figure(figsize=(12, 6))
fig = vis.plot_optimization_history(study)
fig.show()

# 获取最佳参数
best_params = study.best_trial.params
best_value = study.best_trial.value
print("最佳参数组合：", best_params)
print("最佳得分：", best_value)

# 创建CatBoost模型
catboost_model = CatBoostRegressor(**best_params, random_state=42, loss_function='RMSE')
# 训练模型
catboost_model.fit(X_train, y_train)

# 读取测试数据
test_data = pd.read_excel('../data/Q4_test.xlsx')
X_test = test_data
# X_test = data_scale(test_data)

# 进行预测
catboost_predictions = catboost_model.predict(X_test)
# 保留1位小数
result = np.round(catboost_predictions, 1)

# 保存结果
result_data = pd.read_excel('../data/附件四（Excel表）.xlsx')
result_data.iloc[:, 2] = result
result_data.to_excel('../data/附件四（Excel表）.xlsx', index=False)

"""
最佳参数组合： {'depth': 5, 'learning_rate': 0.09035806707859466, 'iterations': 895, 'l2_leaf_reg': 3.212475431263396}
最佳得分： 2642812532.9513454

最佳参数组合： {'depth': 5, 'learning_rate': 0.09999431538925409, 'iterations': 756, 'l2_leaf_reg': 1.0200088008848853}
最佳得分： 3038197405.515311

最佳参数组合： {'iterations': 937, 'learning_rate': 0.20690105376697943, 'depth': 5, 'l2_leaf_reg': 0.6516379410481437}       
最佳得分： 2810636473.590898

"""
